﻿using System;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;


namespace ProgramerInput
{



    /// <summary>
    /// Description of CommonHelper.
    /// </summary>
    public static class CommonHelper
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern int GetWindowText(IntPtr hwnd, StringBuilder text, int maxLength);

        public static void ThreadSleep(int ms)
        {
            Thread.Sleep(ms);
        }

        public static void ExecuteKey(string s)
        {
            SendKeys.SendWait(s);
        }

        public static void ExecuteText(string s)
        {
            var sObj = Clipboard.GetDataObject();
            Clipboard.SetText(s);
            SendKeys.SendWait("^v");
            Clipboard.SetDataObject(sObj);
            //SendKeys.Send(s);
        }

        public static void ExecuteLoad(string s)
        {
            if (!s.Contains("."))
            {
                s = s + ".txt";
            }
            var fp = Program.path + "\\" + s;
            //			SendKeys.Send(fp);
            fp = System.IO.File.ReadAllText(fp);
            SendKeys.Send(fp);
        }

        public static void ExecuteRuns(string s)
        {
            //var fp=Program.path+"\\"+s;

            try
            {
                var p = new System.Diagnostics.Process();
                p.StartInfo.FileName = s;//需要启动的程序名
                p.Start();//启动
            }
            catch (Exception)
            {

            }

        }

        public static bool CheckWin(string s,out string ws)
        {
            try
            {
                var wsb = new StringBuilder();
                GetWindowText(GetForegroundWindow(), wsb, 100);
                var wss = wsb.ToString();
                ws = wss;
                if (wss.ToLower().Contains(s.ToLower()))
                {
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                ws = "error";
                return false;
            }
        }

        public static T ToObject<T>(string jsonString)
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
            }
        }

        public static string ToString(object jsonObject)
        {
            using (var ms = new MemoryStream())
            {
                new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
    }
}
